package com.hzy.controller;

import com.hzy.pojo.Result;
import com.hzy.pojo.User;
import com.hzy.service.UserService;
import com.hzy.utils.JwtUtil;
import com.hzy.utils.Md5Util;
import com.hzy.utils.ThreadLocalUtil;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.swing.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Parameters({
            @Parameter(name = "username",required = true),
            @Parameter(name = "password",required = true)
    })
    @PostMapping("/register")
    public Result register(@Pattern(regexp="^\\S{5,16}$") String username,@Pattern(regexp="^\\S{5,16}$") String password){
        //查询
        User user = userService.findByUserName(username);
        if(user==null){
            //注册
            userService.register(username,password);
            return Result.success();
        }else{
            return Result.error("用户名已被占用");
        }
    }

    @Parameters({
            @Parameter(name = "username",required = true),
            @Parameter(name = "password",required = true)
    })
    @PostMapping("/login")
    public Result login(@Pattern(regexp="^\\S{5,16}$") String username,@Pattern(regexp="^\\S{5,16}$") String password){
        User loginUser = userService.findByUserName(username);
        if(loginUser == null){
            return Result.error("用户名错误");
        }
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            //把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }else{
            return Result.error("密码错误");
        }
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/){
        /*Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");*/
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success("更新成功");
    }

    @Parameters({
            @Parameter(name = "avatarUrl",required = true)
    })
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @Validated String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @Parameters({
            @Parameter(name = "old_pwd",required = true),
            @Parameter(name = "new_pwd",required = true),
            @Parameter(name = "re_pwd",required = true)
    })
    @PatchMapping("/updatePwd")
    public Result updatePwd( @RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        //校验参数
        //查询旧密码是否合规
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要参数");
        }
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        String password = userService.findByUserName(username).getPassword();
        if (!password.equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("旧密码不正确");
        }
        if (!newPwd.equals(rePwd)){
            return Result.error("两次输入的新密码不一致");
        }
        userService.updatePwd(newPwd);
        //删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
